package com.sun.controller;

import okhttp3.*;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 模拟推送数据到VictoriaMetrics
 */
public class MockVictoriaMetrics {

    public static OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS).build();

    private static final String VICTORIA_METRICS_RUL = "http://localhost:8428/api/v1";
    private static final String IMPORT = "/import/prometheus";
    private static final String QUERY = "/query?query=";


    public static void main(String[] args) throws Exception {
        // metric: test_metric_3{CPU="111", GPU="222", job="sun-job1"}
        // value: 1.06
        String metricName = "test_metric_3";
        String reqParams = metricName + "{CPU=\"111\", GPU=\"222\", job=\"sun-job1\"} 1.06";
        doPost(reqParams);

        doGet(VICTORIA_METRICS_RUL + QUERY + metricName);
    }

    public static void doGet(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Response response = okHttpClient.newCall(request).execute();
        String result = Objects.requireNonNull(response.body()).string();
        System.out.println("doGet result = " + result);
    }

    public static void doPost(String reqParams) throws Exception {
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, reqParams);
        Request request = new Request.Builder()
                .url(VICTORIA_METRICS_RUL + IMPORT)
                .post(body)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        System.out.println("推送完成！");
        Objects.requireNonNull(response.body()).string();
    }

}
